package com.itheima.controller;

import com.github.pagehelper.PageInfo;
import com.itheima.controller.result.Code;
import com.itheima.controller.result.Result;
import com.itheima.domain.User;
import com.itheima.service.UserService;
import com.itheima.system.exception.BusinessException;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.web.bind.annotation.*;

//RestCntroller是controller和restponseBody合起来的写法
@RestController
@RequestMapping("/user")
public class UserController {

    @Reference
    private UserService userService;

    @PostMapping
    public Result save(User user) {
        boolean save = userService.save(user);
        Result result = new Result();
        if (save ==true) {
             result.setCode(Code.SAVE_OK);
             return result;
        }
        result.setCode(Code.SAVE_FALSE);
        return result;
    }

    @PutMapping
    public Result update(User user) {
        boolean update = userService.update(user);
        Result result = new Result();
        if (update == true) {
            result.setCode(Code.UPDATE_OK);
            return result;
        }
        result.setCode(Code.UPDATE_FALSE);
        return result;
    }

    @DeleteMapping("/{uuid}")
    public Result delete(@PathVariable Integer uuid) {
        boolean delete = userService.delete(uuid);
        Result result = new Result();
        if (delete == true) {
            result.setCode(Code.DELETE_OK);
            return result;
        }
        result.setCode(Code.DELETE_FALSE);
        return result;
    }

    @GetMapping("/{uuid}")
    public Result get(@PathVariable Integer uuid) {
        User user = userService.get(uuid);
        if(uuid==10) throw new BusinessException("出错啦!",Code.GET_FALSE);
        Result result = new Result();
        if (user!=null) {
            result.setCode(Code.GET_OK);
            result.setData(user);
            return result;
        }
        result.setCode(Code.GET_FALSE);
        result.setData(user);
        return result;
    }

    @GetMapping("/{page}/{size}")
    public Result getAll(@PathVariable Integer page, @PathVariable Integer size) {
        PageInfo<User> all = userService.getAll(page, size);
        Result result = new Result();
        if (all!=null) {
            result.setCode(Code.GET_OK);
            result.setData(all);
            return result;
        }
        result.setCode(Code.GET_FALSE);
        result.setData(all);
        return result;
    }

    @PostMapping("/login")
    public Result login(String userName, String password) {
        User login = userService.login(userName, password);
        Result result = new Result();
        if (login!=null) {
            result.setCode(Code.GET_OK);
            result.setData(login);
            return result;
        }
        result.setCode(Code.GET_FALSE);
        result.setData(login);
        return result;
    }
}
